﻿using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Manager.Database;
using Manager.Model;
using Manager.Model.Dto;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace Manager.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly PCCSContext _context;

        //通过依赖注入的方式将 IConfiguration 注入到你的控制器或服务中
        private readonly IConfiguration _configuration;

        // 通过构造函数注入 DbContext
        public AuthController(PCCSContext context, IConfiguration configuration)
        {
            _context = context;
            _configuration = configuration;
        }

        [HttpPost("login")]
        public async Task<ObjectResult> Login([FromBody] UserDto userDto)
        {
            var dbUser = await _context.users.FirstOrDefaultAsync(u =>
                u.username == userDto.username && u.password == userDto.password
            );
            if (dbUser != null)
            {
                var user_token = GenerateToken(dbUser);
                return new ObjectResult(
                    new
                    {
                        success = true,
                        user = dbUser,
                        token = user_token
                    }
                );
            }
            else
            {
                return new ObjectResult(new { success = false, message = "用户名或密码错误" });
            }
        }

        [HttpPost("updatePassword")]
        public async Task<ObjectResult> UpdatePassword([FromBody] PasswordDto passwordDto)
        {
            var user = await _context.users.FirstOrDefaultAsync(u => u.id == passwordDto.userId);
            if (user != null)
            {
                user.password = passwordDto.newPassword;
                _context.users.Update(user);
                await _context.SaveChangesAsync();
                return new ObjectResult(new { success = true, message = "密码修改成功" });
            }
            else
            {
                return new ObjectResult(new { success = false, message = "用户不存在" });
            }
        }

        /// <summary>
        /// token生成
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string GenerateToken(User user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var secretKey = _configuration["JwtSettings:SecretKey"];

            var key = Encoding.ASCII.GetBytes(secretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(
                    new Claim[] { new Claim(ClaimTypes.Name, user.username) }
                ),
                Expires = DateTime.UtcNow.AddHours(1),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature
                )
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}
